/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;



import domain.Invoice;
import domain.Waterconsumption;
import domain.Watercontract;
import java.sql.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

/**
 *
 * @author Alejandro
 */
public class WaterconsumptionDao {
    EntityManager em;
    EntityTransaction tx;

    public WaterconsumptionDao() {
        em = SingletonDao.getInstance().getEntityManager();
        tx = SingletonDao.getTx();
    }

    public Waterconsumption getWaterconsumption(Integer idW){
        Waterconsumption m = (Waterconsumption) em.createNativeQuery("select * from waterconsumption as w where w.idWaterCons='"+idW+"'", Waterconsumption.class).getSingleResult();
        return m;
    }

    public void saveWaterconsumption(Waterconsumption w){
        tx.begin();
        em.persist(w);
        tx.commit();
    }

    public void removeWaterconsumption(Waterconsumption w){
        tx.begin();
        em.remove(w);
        tx.commit();
    }

    public Waterconsumption getWaterconsumptionDate(Watercontract m){
        Waterconsumption ec = null;
        Date date = new Date(new java.util.Date().getTime());
        int month = date.getMonth();
        int year = date.getYear()+1900;
        int day = date.getDate();
        List list = em.createNativeQuery("select * from waterconsumption as e, contract as cont, consumption as cons where cont.idContract='"+m.getContract().getIdContract()+"' and  e.consFK=cons.idCons and cons.consFk=cont.idContract and e.dateTo>'"+year+"-"+month+"-"+day+"'", Waterconsumption.class).getResultList();
        if(!list.isEmpty()){
            ec = (Waterconsumption) list.get(0);
        }
        return ec;
    }

    public List<Waterconsumption> getWaterListConsumption(Invoice i){
        List<Waterconsumption> l = em.createNativeQuery("select * from waterconsumption as wc where wc.invoiceFK ='"+i.getIdInvoice()+"'", Waterconsumption.class).getResultList();
        return l;
    }



}
